from tuntun.settings import r as rc
import json

class SortedSet(object):
    """ Sorted Set"""
    def __init__(self, key, r=None):
        self.key = key
        self.r = r if r else rc

    def add(self, **kwargs):
        """
        add(a=1, b=2)
        """
        return self.r.zadd(self.key, **kwargs)

    def increment(self, name, score=1):
        """
        increament(a, 10)
        """
        return self.r.zincrby(self.key, name, score)

    def range_desc(self, start, stop, withscores=True):
        """Get Range And Desc Order:  High -> Low"""
        if withscores:
            return self.r.zrevrange(self.key, start, stop, 'withscores')
        else:
            return self.r.zrevrange(self.key, start, stop)

    def rank(self, name):
        """ Get Rank in Low->High"""
        return self.r.zrank(self.key, name)


class String(object):
    def __init__(self, key, r=None):
        self.key = key
        self.r = r if r else rc

    def set(self, value, from_python=False):
        if from_python:
            value = json.dumps(value)
        return self.r.set(self.key, value)

    def get(self, to_python=False):
        value = self.r.get(self.key)
        print(value)
        if to_python:
            value = json.loads(value)
        return value
